﻿using System;
using LitJson;
using Sliver.Network.Components;
using UnityEngine;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace Sliver.Roadnet.Network
{
    public class WebsocketHandlerMain : WebSocketBehavior
    {
        protected override void OnOpen()
        {
            Debug.Log("websocket server started!");
        }

        // protected override async Task OnOpen()
        // {
        //     Debug.Log("websocket server started!");
        // }

        protected override void OnMessage(MessageEventArgs e)
        {
            Debug.Log(e.Data);
            try
            {
                MessageIn msg_in = JsonMapper.ToObject<MessageIn>(e.Data);
                MessageOut msg_out = msg_in.ToOut();

                switch (msg_in.path)
                {
                    case "frame":
                        msg_out.data = MainSceneManager.Instance.roadnet.GetSnap();
                        break;
                }

                Send(msg_out.ToJson());
            }
            catch (Exception exception)
            {
                Debug.Log(exception);
            }
        }

        protected override void OnError(ErrorEventArgs e)
        {
            Debug.Log(e.Message);
        }

        protected override void OnClose(CloseEventArgs e)
        {
            Debug.Log("close");
        }
    }
}
